﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace NBusiness.Data
{
    public static class CommandManager
    {
        private static Queue<CommandBase> _commands = new Queue<CommandBase>();

        public static void Enqueue(CommandBase command)
        {
            command.Initialize();
            command.Completed += new EventHandler(command_Completed);

            lock (_commands)
            {
                _commands.Enqueue(command);
                if (_commands.Count == 1)
                    RunNext();                
            }
        }

        static void command_Completed(object sender, EventArgs e)
        {
            lock (_commands)
                _commands.Dequeue();

            (sender as CommandBase).Completed -= new EventHandler(command_Completed);

            RunNext();
        }

        private static void RunNext()
        {
            CommandBase next = null;
            lock (_commands)
                next = _commands.Peek();

            if (next != null)
                next.Run();
        }

        public static void Join() 
        {
            CommandBase[] commands = null;
            lock (_commands)
                commands = _commands.ToArray();

            foreach (CommandBase command in commands)
                command.Join();
        }
    }
}
